package com.px.controller;

import com.px.dto.ReturnResult;
import com.px.dto.ReturnResultUtils;
import com.px.pojo.ShUser;
import com.px.service.DxUserService;
import com.px.service.MaiService;
import com.px.service.MaiUserService;
import com.px.utils.MD5Utils;
import com.px.utils.RedisUtils;
import com.px.vo.UserVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
public class MaiUserController {
    @Resource
    private DxUserService dxUserService;
    @Resource
    private MaiService maiService;
    @Resource
    private RedisUtils redisUtils;
    @Resource
    private MaiUserService maiUserService;
    /**
     * qq邮箱
     * @param
     * @param
     * @param
     * @return
     * @throws Exception
     */
    @PostMapping("/mai")
    ReturnResult mailMessage(UserVo userVo)throws Exception{
        //获取邮箱
        String code = userVo.getAccount();
        //邮箱模板
        String mailCodeRegex="^[A-Za-z0-9\\u4e00-\\u9fa5]+@[a-zA-Z0-9_-]+(.[a-zA-Z0-9_-]+)$";
        //判断邮箱是否已经被注册
        if (StringUtils.isNotBlank(code) && code.matches(mailCodeRegex)){

            //获取邮箱的数据
            ShUser userByUserCode = dxUserService.cz(code);

            //判断邮箱是否存在
            if (userByUserCode != null) {
                return ReturnResultUtils.returnFail(2008,"QQ邮箱已存在");
            }

            //生成随机数
            String ss = MD5Utils.getRandomCode() + "";

            //传参，第一个是发送人邮箱，第一个是接受人邮箱也就是获取的邮箱，第三个是验证码
            boolean result = maiService.mailMessage("2838721763@qq.com", code, ss);
            if (result){
                //设置个key
                String key = "activeMail："+code;

                //添加进redis
                redisUtils.set(key,ss,60*10L);

                return maiUserService.mai(userVo);
            }else {
                return ReturnResultUtils.returnFail(2005,"QQ邮箱格式不正确，注册失败");
            }
        }else {
            return ReturnResultUtils.returnFail(2008,"邮箱格式不正确，注册失败");
        }
    }
}
